<template>
  <div>
    <el-alert
      :closable="false"
      title="注意：只允许为第三级分类设置相关参数！"
      type="warning"
      center
      effect="dark"
      show-icon
    >
    </el-alert>
    <div style="margin: 20px 0">
      选择商品分类：
      <el-cascader
        :options="cascaderList"
        v-model="delfKeys"
        :props="{ checkStrictly: true, value: 'cat_id', label: 'cat_name' }"
        clearable
        @change="changeCascder"
      ></el-cascader>
    </div>
    <el-tabs
      @tab-click="handleClick(activeIndex)"
      type="border-card"
      v-model="activeIndex"
    >
      <el-tab-pane label="动态属性" name="many">
        <el-button
          :disabled="isDisabled"
          @click="addAttr"
          type="primary"
          size="mini"
          >添加参数</el-button
        >
        <el-table :data="manyTable">
          <el-table-column type="expand">
            <template scope="scope">
              <el-tag
                style="margin-right: 12px"
                v-for="(tag, i) in scope.row.attr_vals"
                :key="tag"
                closable
                :disable-transitions="false"
                @close="handleClose(i, scope.row)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                style="width: 200px"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
                >+ New Tag</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="#" type="index"> </el-table-column>
          <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
          <el-table-column label="操作">
            <template scope="scope">
              <el-button size="mini" type="primary" @click="editAttr(scope.row)"
                >编辑<i class="el-icon-edit"></i
              ></el-button>
              <el-button size="mini" type="danger" @click="delFn(scope.row.attr_id)"
                >删除<i class="el-icon-delete"></i
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态属性" name="only">
        <el-button
          :disabled="isDisabled"
          @click="addAttr"
          type="primary"
          size="mini"
          >添加属性</el-button
        >
        <el-table :data="onlyTable">
          <el-table-column type="expand">
            <template scope="scope">
              <el-tag
                style="margin-right: 12px"
                v-for="(tag, i) in scope.row.attr_vals"
                :key="tag"
                closable
                :disable-transitions="false"
                @close="handleClose(i, scope.row)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                style="width: 200px"
                v-if="scope.row.inputVisible"
                v-model="scope.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scope.row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scope.row)"
                >+ New Tag</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="#" type="index"> </el-table-column>
          <el-table-column prop="attr_name" label="属性名称"> </el-table-column>
          <el-table-column label="操作">
            <template scope="scope">
              <el-button @click="editAttr(scope.row)" size="mini" type="primary"
                >编辑<i class="el-icon-edit"></i
              ></el-button>
              <el-button size="mini" type="danger" @click="delFn(scope.row.attr_id)"
                >删除<i class="el-icon-delete"></i
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      @close="colseaddAttr"
      title="新增属性"
      :visible.sync="addAttrShow"
    >
      <el-form
        label-width="100px"
        clearable
        ref="addform"
        :rules="rules"
        v-if="addAttrShow"
        :model="form"
      >
        <el-form-item
          :label="activeIndex === 'many' ? '动态参数' : '静态参数'"
          prop="attr_name"
        >
          <el-input v-model="form.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="colseaddAttr">取 消</el-button>
        <el-button type="primary" @click="handleSumbit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCategoriesList } from '../../api/categories';
import {
  getAttributesList,
  addAttributes,
  addxiaoAttributes,
  delAttributes,
} from '../../api/params';

export default {
  data() {
    return {
      addAttrShow: false,
      activeIndex: 'many',
      cascaderList: [],
      delfKeys: [],
      manyTable: [],
      onlyTable: [],
      form: {
        attr_name: '',
      },
      rules: {
        attr_name: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      isEdit: false,
      editId: null,
    };
  },
  methods: {
    delFn(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const res = await delAttributes(this.delfKeys[2], id);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.getAttrList();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        });
      });
    },
    // 做编辑
    handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.saveFn(row);
    },
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleInputConfirm(row) {
      // 如果为空
      if (row.inputValue.trim().length === 0) {
        row.inputValue = '';
        row.inputVisible = false;
      }
      // 如果没有return，则说明有输入的内容，需要做后续的处理
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = '';
      row.inputVisible = false;
      // 需要发起请求保存操作
      this.saveFn(row);
    },
    async saveFn(row) {
      const res = await addxiaoAttributes(this.delfKeys[2], row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' '),
      });
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败！');
      }
      this.$message.success('修改参数项成功！');
    },
    colseaddAttr() {
      this.$refs.addform.resetFields();
      this.addAttrShow = false;
    },
    handleSumbit() {
      this.$refs.addform.validate((valid) => {
        if (!valid) return false;
        this.isEdit ? this.onEdit() : this.onAdd();
      });
    },
    editAttr(row) {
      this.isEdit = true;
      this.addAttrShow = true;
      this.editId = row.attr_id;
      this.form.attr_name = row.attr_name;
    },
    // 做编辑
    async onEdit() {
      const params = {
        attr_name: this.form.attr_name,
        attr_sel: this.activeIndex,
      };
      const res = await addxiaoAttributes(this.delfKeys[2], this.editId, params);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getAttrList();
      this.colseaddAttr();
    },
    // 做添加
    async onAdd() {
      const params = {
        attr_name: this.form.attr_name,
        attr_sel: this.activeIndex,
      };
      const res = await addAttributes(this.delfKeys[2], params);
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
      this.getAttrList();
      this.colseaddAttr();
    },
    // 添加参数
    addAttr() {
      this.form.attr_name = '';
      this.isEdit = false;
      this.addAttrShow = true;
    },
    // // tabs 切换
    handleClick(name) {
      if (this.delfKeys.length !== 3) return false;
      this.activeIndex = name;
      this.getAttrList();
    },
    async getAttrList() {
      const res = await getAttributesList(this.delfKeys[2], {
        sel: this.activeIndex,
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
        // 添加一个布尔值，控制文本框的显示与隐藏
        item.inputVisible = false;
        // 文本框中输入的值
        item.inputValue = '';
      });
      if (this.activeIndex === 'many') {
        this.manyTable = res.data;
      } else {
        this.onlyTable = res.data;
      }
    },
    // 选择器的change
    changeCascder() {
      if (this.delfKeys.length !== 3) return false;
      this.getAttrList();
    },
    // 获取分类参数
    async getOptions() {
      const params = {
        type: 3,
      };
      const res = await getCategoriesList(params);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cascaderList = res.data;
    },
  },
  created() {
    this.getOptions();
  },
  computed: {
    // 按钮禁用  当选中三级分类时才开启
    isDisabled() {
      if (this.delfKeys.length !== 3) {
        return true;
      }
      return false;
    },
  },
};
</script>

<style>
</style>
